<template>
  <div class="life-entities">
    <!-- 页面标题和操作 -->
    <div class="page-header">
      <div class="header-content">
        <h2>生命体管理</h2>
        <p>管理和监控所有数字生命体的状态和行为</p>
      </div>
      <div class="header-actions">
        <a-space>
          <!-- 实时状态指示器 -->
          <a-badge :status="isConnected ? 'success' : 'error'" :text="isConnected ? '实时连接' : '连接断开'" />
          
          <!-- 自动刷新控制 -->
          <a-button 
            :type="autoRefresh ? 'primary' : 'default'" 
            size="small"
            @click="toggleAutoRefresh"
          >
            <template #icon><wifi-outlined /></template>
            {{ autoRefresh ? '自动刷新' : '手动刷新' }}
          </a-button>
          
          <!-- 手动刷新 -->
          <a-button @click="loadData" :loading="loading">
            <template #icon><reload-outlined /></template>
            刷新
          </a-button>
          
          <!-- 创建按钮 -->
          <a-button type="primary" @click="showCreateModal">
            <template #icon><plus-outlined /></template>
            创建生命体
          </a-button>
        </a-space>
      </div>
    </div>

    <!-- 搜索和筛选 -->
    <a-card class="search-card" :bordered="false">
      <a-row :gutter="16">
        <a-col :xs="24" :sm="8" :md="6">
          <a-input
            v-model:value="searchForm.search"
            placeholder="搜索生命体名称"
            allow-clear
            @change="handleSearch"
          >
            <template #prefix><search-outlined /></template>
          </a-input>
        </a-col>
        <a-col :xs="24" :sm="8" :md="6">
          <a-select
            v-model:value="searchForm.type"
            placeholder="选择类型"
            allow-clear
            @change="handleSearch"
          >
            <a-select-option value="CORPORATE">企业</a-select-option>
            <a-select-option value="URBAN">城市</a-select-option>
            <a-select-option value="CONCEPTUAL">概念</a-select-option>
            <a-select-option value="INDIVIDUAL">个体</a-select-option>
            <a-select-option value="HYBRID">混合</a-select-option>
            <a-select-option value="SYSTEM">系统</a-select-option>
          </a-select>
        </a-col>
        <a-col :xs="24" :sm="8" :md="6">
          <a-select
            v-model:value="searchForm.status"
            placeholder="选择状态"
            allow-clear
            @change="handleSearch"
          >
            <a-select-option value="ACTIVE">活跃</a-select-option>
            <a-select-option value="INACTIVE">非活跃</a-select-option>
            <a-select-option value="EVOLVING">进化中</a-select-option>
            <a-select-option value="DORMANT">休眠</a-select-option>
          </a-select>
        </a-col>
        <a-col :xs="24" :sm="24" :md="6">
          <a-space>
            <a-button @click="handleReset">重置</a-button>
            <a-button type="primary" @click="handleSearch">搜索</a-button>
          </a-space>
        </a-col>
      </a-row>
    </a-card>

    <!-- 数据表格 -->
    <a-card :bordered="false">
      <a-table
        :columns="columns"
        :data-source="dataSource"
        :loading="loading"
        :pagination="pagination"
        row-key="id"
        @change="handleTableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'type'">
            <a-tag :color="getTypeColor(record.type)">
              {{ getTypeLabel(record.type) }}
            </a-tag>
          </template>

          <template v-if="column.key === 'status'">
            <a-badge
              :status="getStatusBadge(record.status)"
              :text="getStatusLabel(record.status)"
            />
          </template>

          <template v-if="column.key === 'createdAt'">
            {{ formatDate(record.createdAt) }}
          </template>

          <template v-if="column.key === 'action'">
            <a-space>
              <a-button type="link" size="small" @click="viewDetail(record)"> 查看 </a-button>
              <a-button type="link" size="small" @click="editEntity(record)"> 编辑 </a-button>
              
              <!-- 状态操作 -->
              <a-dropdown>
                <a-button type="link" size="small">
                  状态 <down-outlined />
                </a-button>
                <template #overlay>
                  <a-menu>
                    <a-menu-item key="activate" @click="activateEntity(record)" :disabled="record.status === 'ACTIVE'">
                      激活
                    </a-menu-item>
                    <a-menu-item key="dormant" @click="dormantEntity(record)" :disabled="record.status === 'DORMANT'">
                      休眠
                    </a-menu-item>
                    <a-menu-item key="evolve" @click="evolveEntity(record)" :disabled="record.status !== 'ACTIVE'">
                      进化
                    </a-menu-item>
                  </a-menu>
                </template>
              </a-dropdown>
              
              <a-popconfirm title="确定要删除这个生命体吗？" @confirm="deleteEntity(record)">
                <a-button type="link" size="small" danger> 删除 </a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 创建/编辑模态框 -->
    <a-modal
      v-model:open="modalVisible"
      :title="modalTitle"
      width="600px"
      @ok="handleModalOk"
      @cancel="handleModalCancel"
    >
      <a-form ref="formRef" :model="formData" :rules="formRules" layout="vertical">
        <a-form-item label="名称" name="name">
          <a-input v-model:value="formData.name" placeholder="请输入生命体名称" />
        </a-form-item>

        <a-form-item label="类型" name="type">
          <a-select v-model:value="formData.type" placeholder="请选择类型">
            <a-select-option value="CORPORATE">企业</a-select-option>
            <a-select-option value="URBAN">城市</a-select-option>
            <a-select-option value="CONCEPTUAL">概念</a-select-option>
            <a-select-option value="INDIVIDUAL">个体</a-select-option>
            <a-select-option value="HYBRID">混合</a-select-option>
            <a-select-option value="SYSTEM">系统</a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="父生命体ID" name="parentId">
          <a-input v-model:value="formData.parentId" placeholder="请输入父生命体ID（可选）" />
        </a-form-item>

        <a-form-item label="描述" name="description">
          <a-textarea v-model:value="formData.description" placeholder="请输入描述信息" :rows="3" />
        </a-form-item>

        <a-form-item label="配置" name="configuration">
          <a-textarea v-model:value="formData.configuration" placeholder="请输入配置信息（JSON格式，可选）" :rows="2" />
        </a-form-item>

        <a-form-item label="元数据" name="metadata">
          <a-textarea v-model:value="formData.metadata" placeholder="请输入元数据（JSON格式，可选）" :rows="2" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import { PlusOutlined, SearchOutlined, ReloadOutlined, WifiOutlined, DownOutlined } from '@ant-design/icons-vue'
import { lifeEntityApi } from '@/api/lifeEntity'
import { useLifeEntityRealtime } from '@/composables/useLifeEntityRealtime'
import type { LifeEntity, LifeEntityType, LifeEntityStatus, LifeEntityCreateRequest, LifeEntityUpdateRequest } from '@/api/types'

const router = useRouter()

// 实时更新功能
const { isConnected, lastUpdate, addEventListener, removeEventListener } = useLifeEntityRealtime()

// 响应式数据
const loading = ref(false)
const dataSource = ref<LifeEntity[]>([])
const modalVisible = ref(false)
const modalTitle = ref('创建生命体')
const currentEntity = ref<LifeEntity | null>(null)
const autoRefresh = ref(true)

// 搜索表单
const searchForm = reactive({
  search: '',
  type: undefined as LifeEntityType | undefined,
  status: undefined as LifeEntityStatus | undefined,
})

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条记录`,
})

// 表格列配置
const columns = [
  {
    title: '名称',
    dataIndex: 'name',
    key: 'name',
    width: 200,
  },
  {
    title: '类型',
    dataIndex: 'type',
    key: 'type',
    width: 120,
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 120,
  },
  {
    title: '描述',
    dataIndex: 'description',
    key: 'description',
    ellipsis: true,
  },
  {
    title: '创建时间',
    dataIndex: 'createdAt',
    key: 'createdAt',
    width: 180,
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    fixed: 'right',
  },
]

// 表单数据和验证规则
const formRef = ref()
const formData = reactive({
  name: '',
  type: undefined as LifeEntityType | undefined,
  description: '',
  parentId: undefined as string | undefined,
  configuration: '',
  metadata: '',
})

const formRules = {
  name: [{ required: true, message: '请输入生命体名称', trigger: 'blur' }],
  type: [{ required: true, message: '请选择类型', trigger: 'change' }],
}

// 获取类型颜色
const getTypeColor = (type: LifeEntityType) => {
  const colorMap = {
    CORPORATE: 'blue',
    URBAN: 'green',
    CONCEPTUAL: 'purple',
    INDIVIDUAL: 'orange',
    HYBRID: 'red',
    SYSTEM: 'cyan',
  }
  return colorMap[type]
}

// 获取类型标签
const getTypeLabel = (type: LifeEntityType) => {
  const labelMap = {
    CORPORATE: '企业',
    URBAN: '城市',
    CONCEPTUAL: '概念',
    INDIVIDUAL: '个体',
    HYBRID: '混合',
    SYSTEM: '系统',
  }
  return labelMap[type]
}

// 获取状态徽章
const getStatusBadge = (status: LifeEntityStatus) => {
  const badgeMap = {
    ACTIVE: 'success',
    INACTIVE: 'default',
    EVOLVING: 'processing',
    DORMANT: 'warning',
  }
  return badgeMap[status] as any
}

// 获取状态标签
const getStatusLabel = (status: LifeEntityStatus) => {
  const labelMap = {
    ACTIVE: '活跃',
    INACTIVE: '非活跃',
    EVOLVING: '进化中',
    DORMANT: '休眠',
  }
  return labelMap[status]
}

// 格式化日期
const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleString('zh-CN')
}

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.current - 1,
      size: pagination.pageSize,
      sort: 'createdAt',
      direction: 'desc',
      ...searchForm,
    }

    const response = await lifeEntityApi.getList(params)
    dataSource.value = response.content
    pagination.total = response.totalElements
  } catch (error) {
    message.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

// 搜索处理
const handleSearch = () => {
  pagination.current = 1
  loadData()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    search: '',
    type: undefined,
    status: undefined,
  })
  handleSearch()
}

// 表格变化处理
const handleTableChange = (pag: any) => {
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
  loadData()
}

// 显示创建模态框
const showCreateModal = () => {
  modalTitle.value = '创建生命体'
  currentEntity.value = null
  Object.assign(formData, {
    name: '',
    type: undefined,
    description: '',
    parentId: undefined,
    configuration: '',
    metadata: '',
  })
  modalVisible.value = true
}

// 查看详情
const viewDetail = (record: LifeEntity) => {
  router.push(`/life-entities/${record.id}`)
}

// 编辑实体
const editEntity = (record: LifeEntity) => {
  modalTitle.value = '编辑生命体'
  currentEntity.value = record
  Object.assign(formData, {
    name: record.name,
    type: record.type,
    description: record.description || '',
    parentId: record.parentId,
    configuration: '',
    metadata: '',
  })
  modalVisible.value = true
}

// 删除实体
const deleteEntity = async (record: LifeEntity) => {
  try {
    await lifeEntityApi.delete(record.id)
    message.success('删除成功')
    loadData()
  } catch (error) {
    message.error('删除失败')
  }
}

// 激活生命体
const activateEntity = async (record: LifeEntity) => {
  try {
    await lifeEntityApi.activate(record.id)
    message.success('激活成功')
    loadData()
  } catch (error) {
    message.error('激活失败')
  }
}

// 休眠生命体
const dormantEntity = async (record: LifeEntity) => {
  try {
    await lifeEntityApi.dormant(record.id)
    message.success('休眠成功')
    loadData()
  } catch (error) {
    message.error('休眠失败')
  }
}

// 进化生命体
const evolveEntity = async (record: LifeEntity) => {
  try {
    await lifeEntityApi.evolve(record.id)
    message.success('进化成功')
    loadData()
  } catch (error) {
    message.error('进化失败')
  }
}

// 模态框确认
const handleModalOk = async () => {
  try {
    await formRef.value.validate()

    if (currentEntity.value) {
      // 编辑
      const updateData: LifeEntityUpdateRequest = {
        name: formData.name,
        type: formData.type,
        description: formData.description,
        configuration: formData.configuration || undefined,
        metadata: formData.metadata || undefined,
      }
      await lifeEntityApi.update(currentEntity.value.id, updateData)
      message.success('更新成功')
    } else {
      // 创建
      const createData: LifeEntityCreateRequest = {
        name: formData.name,
        type: formData.type!,
        description: formData.description || undefined,
        parentId: formData.parentId || undefined,
        configuration: formData.configuration || undefined,
        metadata: formData.metadata || undefined,
      }
      await lifeEntityApi.create(createData)
      message.success('创建成功')
    }

    modalVisible.value = false
    loadData()
  } catch (error: any) {
    if (error.errorFields) {
      // 表单验证错误
      return
    }
    message.error('操作失败')
  }
}

// 模态框取消
const handleModalCancel = () => {
  modalVisible.value = false
}

// 实时更新处理
const handleEntityUpdate = (event: any) => {
  if (autoRefresh.value) {
    // 如果是当前页面的数据，直接更新
    if (event.entity) {
      const index = dataSource.value.findIndex(item => item.id === event.entity.id)
      if (index > -1) {
        dataSource.value[index] = event.entity
      } else if (event.type === 'ENTITY_CREATED') {
        // 新创建的实体，重新加载数据
        loadData()
      }
    } else if (event.type === 'ENTITY_DELETED') {
      // 删除实体
      dataSource.value = dataSource.value.filter(item => item.id !== event.entityId)
      pagination.total = Math.max(0, pagination.total - 1)
    }
  }
}

// 切换自动刷新
const toggleAutoRefresh = () => {
  autoRefresh.value = !autoRefresh.value
  message.info(autoRefresh.value ? '已开启自动刷新' : '已关闭自动刷新')
}

onMounted(() => {
  loadData()
  
  // 注册实时更新监听器
  addEventListener('ENTITY_CREATED', handleEntityUpdate)
  addEventListener('ENTITY_UPDATED', handleEntityUpdate)
  addEventListener('ENTITY_DELETED', handleEntityUpdate)
  addEventListener('STATUS_CHANGED', handleEntityUpdate)
})

onUnmounted(() => {
  // 移除监听器
  removeEventListener('ENTITY_CREATED', handleEntityUpdate)
  removeEventListener('ENTITY_UPDATED', handleEntityUpdate)
  removeEventListener('ENTITY_DELETED', handleEntityUpdate)
  removeEventListener('STATUS_CHANGED', handleEntityUpdate)
})
</script>

<style scoped>
.life-entities {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 24px;
}

.header-content h2 {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
}

.header-content p {
  margin: 0;
  color: #666;
}

.search-card {
  margin-bottom: 16px;
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: stretch;
  }

  .header-actions {
    margin-top: 16px;
  }
}
</style>
